package controllers

import (
	"beeblog/models"
	"github.com/astaxie/beego"
)

type TopicController struct {
	beego.Controller
}

func (this *TopicController) Get() {
	this.Data["isTopic"] = true
	topicList, err := models.AllTopic(false)
	if err == nil {
		this.Data["topicList"] = topicList
	}
	this.Data["isLogin"] = checkLoginStatus(this.Controller)
	this.TplName = "topic.html"
}

func (this *TopicController) Post() {
	// 身份校验
	if !checkLoginStatus(this.Controller) {
		this.Redirect("/login", 301)
	}

	title := this.Input().Get("title")
	content := this.Input().Get("content")
	tid := this.Input().Get("tid")
	var err error
	if tid != "" {
		err = models.ModifyTopic(tid, title, content)
	} else {
		err = models.AddTopic(title, content)
	}
	if err != nil {
		beego.Error(err)
	}

	this.Redirect("/topic", 301)
}

func (this *TopicController) Add() {
	this.TplName = "add_topic.html"
}

func (this *TopicController) View() {
	topicData, _ := models.GetTopic(this.Input().Get("id"))
	this.Data["topicData"] = topicData
	this.TplName = "view_topic.html"

}

func (this *TopicController) Modify() {
	id := this.Input().Get("id")
	this.Data["tid"] = id
	topicInfo, err := models.GetTopic(id)
	if err != nil {
		beego.Error(err)
	}
	this.Data["topicInfo"] = topicInfo
	this.TplName = "add_topic.html"
}
